package com.hx.haowumall.haowumallware.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.hx.common.constant.WareConstant;
import com.hx.haowumall.haowumallware.service.WareSkuService;
import com.hx.haowumall.haowumallware.vo.MergeVo;
import com.hx.haowumall.haowumallware.entity.PurchaseDetailEntity;
import com.hx.haowumall.haowumallware.service.PurchaseDetailService;
import com.hx.haowumall.haowumallware.vo.PurchaseDoneVo;
import com.hx.haowumall.haowumallware.vo.PurchaseItemDoneVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hx.common.utils.PageUtils;
import com.hx.common.utils.Query;

import com.hx.haowumall.haowumallware.dao.PurchaseDao;
import com.hx.haowumall.haowumallware.entity.PurchaseEntity;
import com.hx.haowumall.haowumallware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    PurchaseDetailService detailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status","1")
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {

        Long purchaseId = mergeVo.getPurchaseId();

        if (purchaseId == null){
            //1、新建一个
            PurchaseEntity purchaseEntity = new PurchaseEntity();

            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREARED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }


        PurchaseDetailEntity detailServiceById = detailService.getById(purchaseId);
        // 确认采购单是0，1才可以合并
        if (detailServiceById.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode() ||
        detailServiceById.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREARED.getCode()){
            List<Long> items = mergeVo.getItems();
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> collect = items.stream().map(i -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(i);
                detailEntity.setPurchaseId(finalPurchaseId);
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());

                return detailEntity;
            }).collect(Collectors.toList());

            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);

            detailService.updateBatchById(collect);
        }else {
            log.info("无法合并,状态错误");
        }


    }

    // ids 是采购单的id
    @Override
    public void received(List<Long> ids) {
        //1、确认当前采购单是新建或者已非配
        List<PurchaseEntity> collect = ids.stream().map(item -> {
            PurchaseEntity byId = this.getById(item);
            return byId;
        }).filter(i -> {
            if (i.getStatus() == WareConstant.PurchaseStatusEnum.CREARED.getCode() ||
                    i.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            } else {
                return false;
            }
        }).map(rIds->{
            rIds.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            rIds.setUpdateTime(new Date());
            return rIds;
        }).collect(Collectors.toList());

        //2、改变采购单的状态
        this.updateBatchById(collect);

        //3、改变采购项的状态
        collect.forEach(cItem->{
            List<PurchaseDetailEntity> entities = detailService.listDetailByPurchaseId(cItem.getId());
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(entity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(entity.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());

                return detailEntity;
            }).collect(Collectors.toList());

            detailService.updateBatchById(detailEntities);
        });

    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {

        //2、改变采购项的状态
        Boolean flag = true;

        List<PurchaseItemDoneVo> items = doneVo.getItems();

        ArrayList<PurchaseDetailEntity> updates = new ArrayList<>();

        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();

            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.FAILDED.getCode()){
                flag = false;
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FAILDED.getCode());
            }else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                ////3、将成采购的进行入库
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        detailService.updateBatchById(updates);

        //1、改变采购单的状态
        Long id = doneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);


    }

}